import { getFileUrl, deleteFile } from '../FileSystem/image-processor.js';
import { useMysql } from '../mysql/index.js';
import { MysqlQueryBuilder } from '../mysql/mysql-query-builder.js';

// 文件上传
export const uploadFile = async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ code: 400, message: 'No file uploaded' });
    }

    const { filename, originalname, mimetype, size, path } = req.file;

    // 使用MysqlQueryBuilder构建插入语句
    const insertSql = MysqlQueryBuilder.insert('images', {
      filename,
      originalname,
      mimetype,
      size,
      path
    });

    // 执行SQL
    const result = await useMysql(insertSql);

    res.json({
      code: 200,
      data: {
        id: result.insertId,
        filename,
        originalname,
        mimetype,
        size,
        path,
      },
      message: 'File uploaded successfully'
    });
  } catch (error) {
    console.error('Upload error:', error);
    res.status(500).json({ code: 500, message: 'Server error' });
  }
};
// 获取文件列表
export const getFiles = async (req, res) => {
  try {
    // 使用MysqlQueryBuilder构建查询语句
    const selectSql = MysqlQueryBuilder.select('images', ['*'], {}, {
      orderBy: 'created_at DESC'
    });
    // 数据库信息查找
    const rows = await useMysql(selectSql);
    // 静态资源加入
    const files = rows.map(file => ({
      ...file,
      path: getFileUrl(file.path)
    }));

    res.json({ code: 200, data: files, message: 'Success' });
  } catch (error) {
    console.error('Get files error:', error);
    res.status(500).json({ code: 500, message: 'Server error' });
  }
};
// id查找文件
export const getFileById = async (req, res) => {
  try {
    const { id } = req.params;

    // 使用MysqlQueryBuilder构建查询语句
    const selectSql = MysqlQueryBuilder.select('images', ['*'], { id });
    // 数据库信息查找
    const rows = await useMysql(selectSql);

    if (rows.length === 0) {
      return res.status(404).json({ code: 404, message: 'File not found' });
    }

    const file = rows[0];
    res.json({
      code: 200,
      data: {
        ...file,
        path: getFileUrl(file.path)
      },
      message: 'Success'
    });
  } catch (error) {
    console.error('Get file error:', error);
    res.status(500).json({ code: 500, message: 'Server error' });
  }
};
// 根据id删除文件信息
export const deleteFileById = async (req, res) => {
  try {
    const { id } = req.params;

    // 先查询文件信息
    const selectSql = MysqlQueryBuilder.select('images', ['*'], { id });
    const rows = await useMysql(selectSql);

    if (rows.length === 0) {
      return res.status(404).json({ code: 404, message: 'File not found' });
    }

    const file = rows[0];
console.log(file.path);
    // 删除物理文件
    const fileDeleted = deleteFile(file.path);
    if (!fileDeleted) {
      console.warn(`File not found on disk: ${file.path}`);
    }

    // 删除数据库记录
    const deleteSql = MysqlQueryBuilder.delete('images', { id });
    await useMysql(deleteSql);

    res.json({ code: 200, message: 'File deleted successfully' });
  } catch (error) {
    console.error('Delete file error:', error);
    res.status(500).json({ code: 500, message: 'Server error' });
  }
};